package com.example.gokuplayalong.bases.network;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.gokuplayalong.bases.beans.AppParams;
import com.example.gokuplayalong.bases.beans.Beans;
import com.example.gokuplayalong.bases.exception.ExceptionUtils;
import com.example.gokuplayalong.bases.network.security.Communication;
import com.example.gokuplayalong.bases.network.updown.DownLoad;
import com.example.gokuplayalong.bases.tools.Logger;
import com.example.gokuplayalong.service.fragmentsmanage.SysManagerFragments;
import com.kongzue.dialogx.dialogs.WaitDialog;

import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.util.Objects;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class NetWork extends AsyncTask<String, Void, String> {

    public NetWorkInterface netWorkInterface;
    public int result = 0;

    public int netWorkRun(String serverUrl, Beans beansIn, Context context, NetWorkInterface netWorkInterface) {


        return 0;
    }

    /**
     * 获取当前的网络状态  -1：没有网络  1：WIFI网络  2：wap网络  3：net网络
     */
    public static int getAPNType(Context context) {

        int netType = -1;

        ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
        if (networkInfo == null) {
            return netType;
        }
        int nType = networkInfo.getType();
        if (nType == ConnectivityManager.TYPE_MOBILE) {
            String extraInfo = networkInfo.getExtraInfo();
            if (extraInfo != null && extraInfo.equalsIgnoreCase("cmnet")) {
                netType = 3;
            } else {
                netType = 2;
            }
        } else if (nType == ConnectivityManager.TYPE_WIFI) {
            netType = 1;
        }
        return netType;
    }

    @Override
    protected String doInBackground(String... strings) {
        try {

            //添加全局参数
            JSONObject msgToServer = JSON.parseObject(strings[1]);
            msgToServer.put("versionName", DownLoad.getVersionName());

            Logger.d(" 发送: " + msgToServer);
            OkHttpClient okHttpClient = new OkHttpClient();
            FormBody formBody = new FormBody.Builder().add("msg", new Communication().MessageEncrypt(msgToServer.toJSONString())).build();

            Logger.d(formBody.toString());
            Request request = new Request.Builder().post(formBody).addHeader("Token", StringUtils.isEmpty(AppParams.getInstance().appCurrentUser.getJsonObject().getString("token")) ? "" : AppParams.getInstance().appCurrentUser.getJsonObject().getString("token")).url(strings[0]).build();

            Response response = okHttpClient.newCall(request).execute();

            if (response.isSuccessful()) {
                String msg = response.body().string();
                msg = new Communication().MessageDecrypt(msg);
                Logger.d("收到:" + msg);
                JSONObject msgFromServer = JSON.parseObject(msg);
                if (Objects.equals(msgFromServer.getString("result"), "成功")) {
                    result = 1;
                    netWorkInterface.success(msg);
                } else if (Objects.equals(msgFromServer.getString("result"), "失败")) {
                    result = 0;
                    netWorkInterface.failed(msg);
                    if (msgFromServer.getIntValue("status") == 201) {
                        if (AppParams.getInstance().currentFragment != 0) {
                            AppParams.getInstance().appCurrentUser.getJsonObject().put("Flag", 0);
                            File f = new File(AppParams.getInstance().mediaDir, "currentuser.txt");
                            if (f.exists()) f.delete();
                            SysManagerFragments.switchOnSysFragmentThree("HomeLogin");
                        }
                    }
                }
            }
            WaitDialog.dismiss();

        } catch (Throwable e) {
            WaitDialog.dismiss();

            ExceptionUtils.getException(ExceptionUtils.getTraceInfo(), e);
        }


        return null;
    }


    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);

    }

    public NetWork setInterface(NetWorkInterface netWorkInterface) {
        this.netWorkInterface = netWorkInterface;
        return this;
    }
}
